﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Xml.Serialization;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.GamerServices;
using TradeSea;

namespace TradeSea
{
    public class SaveGame
    {
        public bool hasSaved = false;

        public void Save(string path, string name, Inventory inv)
        {

            //savs the name of the playlist in a variable and allows the user to select any file, txt files, or csv files.
            string fullPath = path + "\\" + name + ".txt";

            //initiates the try method
            try
            {
                //creates the stream writer
                StreamWriter writer;
                //creates a file at the specified path
                writer = File.CreateText(fullPath);
                //for each line in the list, write the contents to the file
                foreach (string s in inv.PrintInvintoryWOamount())
                {
                    //writes the details to the cvs file
                    writer.WriteLine(s);
                }
                //closes the file
                writer.Close();
                hasSaved = true;
            }
            //initiates the catch metod if the program fails
            catch (Exception)
            {
            }
        }
        Stopwatch watch = new Stopwatch();

        public void Draw(SpriteBatch sb, TSContentManager manager, int height)
        {
            if (hasSaved)
            {
                watch.Start();
                if (watch.ElapsedMilliseconds <= 15000) // just lengthed it slightly, minecraft had a issue with a "lag spike of death" because of the same thing
                    sb.DrawString(manager.ConsoleFont, "Game Saved", new Vector2(10, 350), Color.Red);
                else { watch.Stop(); watch.Reset(); hasSaved = false; }
            }
        }


        public Inventory Open(string path)
        {
            Inventory inv = new Inventory();
            StreamReader reader;
            string line;
            try
            {

                reader = File.OpenText(path);

                while (reader.Peek() != -1)
                {
                    line = reader.ReadLine();
                    inv.addToInventory(line);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return inv;
        }
    }
}
